{% extends "base.html" %}

{% block content %}
<!-- 任务管理页面 -->
<div class="content-section">
    <div class="section-header">
        <h2 class="section-title">任务管理</h2>
        <div style="display: flex; gap: 10px;">
            <button class="btn btn-primary" onclick="showRunTaskModal()">执行任务</button>
            <button class="btn btn-primary" onclick="refreshTasks()">刷新</button>
        </div>
    </div>
    <div class="section-content">
        <!-- 快速操作 -->
        <div style="margin-bottom: 20px;">
            <h4>快速操作</h4>
            <div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 15px; margin-top: 10px;">
                <button class="btn btn-primary" onclick="runTask('scrape')">抓取热点</button>
                <button class="btn btn-primary" onclick="runTask('workflow')">执行工作流</button>
                <button class="btn btn-primary" onclick="runTask('health')">健康检查</button>
                <button class="btn btn-primary" onclick="runTask('cleanup')">清理数据</button>
            </div>
        </div>

        <!-- 任务状态监控 -->
        <div style="margin-bottom: 20px;">
            <h4>任务状态监控</h4>
            <div id="taskStatus" style="background: #f8f9fa; padding: 15px; border-radius: 5px; margin-top: 10px;">
                <div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(150px, 1fr)); gap: 15px;">
                    <div style="text-align: center;">
                        <div id="runningTasks" style="font-size: 1.5rem; font-weight: bold; color: #28a745;">0</div>
                        <div style="color: #666;">运行中</div>
                    </div>
                    <div style="text-align: center;">
                        <div id="pendingTasks" style="font-size: 1.5rem; font-weight: bold; color: #ffc107;">0</div>
                        <div style="color: #666;">等待中</div>
                    </div>
                    <div style="text-align: center;">
                        <div id="completedTasks" style="font-size: 1.5rem; font-weight: bold; color: #6c757d;">0</div>
                        <div style="color: #666;">已完成</div>
                    </div>
                    <div style="text-align: center;">
                        <div id="failedTasks" style="font-size: 1.5rem; font-weight: bold; color: #dc3545;">0</div>
                        <div style="color: #666;">失败</div>
                    </div>
                </div>
            </div>
        </div>

        <!-- 任务历史 -->
        <div style="margin-bottom: 20px;">
            <h4>任务历史</h4>
            <div id="taskHistory" style="margin-top: 10px;">
                <!-- 任务历史将通过JavaScript加载 -->
                <div class="empty-state">
                    <p>暂无任务历史记录</p>
                </div>
            </div>
        </div>

        <!-- 定时任务配置 -->
        <div>
            <h4>定时任务配置</h4>
            <div style="margin-top: 10px;">
                <div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(300px, 1fr)); gap: 15px;">
                    <div style="background: #f8f9fa; padding: 15px; border-radius: 5px;">
                        <div style="font-weight: bold; margin-bottom: 10px;">热点抓取</div>
                        <div style="color: #666; font-size: 0.9rem; margin-bottom: 10px;">每30分钟执行一次</div>
                        <div style="display: flex; gap: 10px;">
                            <span class="badge badge-success">启用</span>
                            <button class="btn btn-primary" style="font-size: 0.8rem; padding: 0.25rem 0.5rem;">
                                配置
                            </button>
                        </div>
                    </div>
                    <div style="background: #f8f9fa; padding: 15px; border-radius: 5px;">
                        <div style="font-weight: bold; margin-bottom: 10px;">自动工作流</div>
                        <div style="color: #666; font-size: 0.9rem; margin-bottom: 10px;">每小时执行一次</div>
                        <div style="display: flex; gap: 10px;">
                            <span class="badge badge-success">启用</span>
                            <button class="btn btn-primary" style="font-size: 0.8rem; padding: 0.25rem 0.5rem;">
                                配置
                            </button>
                        </div>
                    </div>
                    <div style="background: #f8f9fa; padding: 15px; border-radius: 5px;">
                        <div style="font-weight: bold; margin-bottom: 10px;">数据清理</div>
                        <div style="color: #666; font-size: 0.9rem; margin-bottom: 10px;">每天凌晨2点执行</div>
                        <div style="display: flex; gap: 10px;">
                            <span class="badge badge-success">启用</span>
                            <button class="btn btn-primary" style="font-size: 0.8rem; padding: 0.25rem 0.5rem;">
                                配置
                            </button>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- 执行任务弹窗 -->
<div id="runTaskModal" style="display: none; position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: rgba(0,0,0,0.5); z-index: 1000;">
    <div style="position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); background: white; padding: 2rem; border-radius: 10px; max-width: 500px; width: 90%;">
        <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 1rem;">
            <h3>执行任务</h3>
            <button onclick="hideRunTaskModal()" style="background: none; border: none; font-size: 1.5rem; cursor: pointer;">&times;</button>
        </div>
        <div>
            <div style="margin-bottom: 15px;">
                <label style="display: block; margin-bottom: 5px;">任务类型:</label>
                <select id="taskTypeSelect" style="width: 100%; padding: 8px; border: 1px solid #ddd; border-radius: 4px;" onchange="updateTaskParams()">
                    <option value="">请选择任务类型</option>
                    <option value="scrape">热点抓取</option>
                    <option value="generate">内容生成</option>
                    <option value="publish">内容发布</option>
                    <option value="workflow">自动工作流</option>
                    <option value="cleanup">数据清理</option>
                    <option value="health">健康检查</option>
                </select>
            </div>
            <div id="taskParams" style="margin-bottom: 15px;"></div>
        </div>
        <div style="text-align: right;">
            <button class="btn" onclick="hideRunTaskModal()" style="margin-right: 10px;">取消</button>
            <button class="btn btn-primary" onclick="executeTask()">执行</button>
        </div>
    </div>
</div>

<!-- 加载提示 -->
<div id="loadingModal" style="display: none; position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: rgba(0,0,0,0.5); z-index: 1000;">
    <div style="position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); background: white; padding: 2rem; border-radius: 10px; text-align: center;">
        <div style="margin-bottom: 1rem;">⏳ 处理中...</div>
        <div id="loadingText">请稍候</div>
    </div>
</div>

<script>
document.addEventListener('DOMContentLoaded', function() {
    loadTaskStatus();
    loadTaskHistory();
    
    // 每10秒刷新一次任务状态
    setInterval(loadTaskStatus, 10000);
});

async function runTask(taskType, params = {}) {
    showLoading(`正在执行${getTaskName(taskType)}任务，请稍候...`);
    
    try {
        const response = await fetch(`/api/v1/tasks/run/${taskType}`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify(params)
        });
        
        const result = await response.json();
        
        if (result.status === 'success') {
            alert(`${getTaskName(taskType)}任务已提交执行！\n任务ID: ${result.task_id}`);
            loadTaskHistory();
        } else {
            alert('任务执行失败：' + (result.message || '未知错误'));
        }
    } catch (error) {
        alert('任务执行失败：' + error.message);
    } finally {
        hideLoading();
    }
}

async function loadTaskStatus() {
    try {
        // 这里可以调用API获取实时任务状态
        // 暂时使用模拟数据
        document.getElementById('runningTasks').textContent = '2';
        document.getElementById('pendingTasks').textContent = '1';
        document.getElementById('completedTasks').textContent = '15';
        document.getElementById('failedTasks').textContent = '1';
    } catch (error) {
        console.error('加载任务状态失败:', error);
    }
}

async function loadTaskHistory() {
    try {
        // 这里可以调用API获取任务历史
        // 暂时使用模拟数据
        const historyContainer = document.getElementById('taskHistory');
        historyContainer.innerHTML = `
            <ul class="item-list">
                <li class="item">
                    <div style="flex: 1;">
                        <div class="item-title">热点抓取任务</div>
                        <div class="item-meta">任务ID: task_123456 | 执行时间: 2024-01-01 12:00:00</div>
                    </div>
                    <div>
                        <span class="badge badge-success">成功</span>
                    </div>
                </li>
                <li class="item">
                    <div style="flex: 1;">
                        <div class="item-title">自动工作流任务</div>
                        <div class="item-meta">任务ID: task_123455 | 执行时间: 2024-01-01 11:00:00</div>
                    </div>
                    <div>
                        <span class="badge badge-warning">运行中</span>
                    </div>
                </li>
            </ul>
        `;
    } catch (error) {
        console.error('加载任务历史失败:', error);
    }
}

function showRunTaskModal() {
    document.getElementById('runTaskModal').style.display = 'block';
}

function hideRunTaskModal() {
    document.getElementById('runTaskModal').style.display = 'none';
}

function updateTaskParams() {
    const taskType = document.getElementById('taskTypeSelect').value;
    const paramsContainer = document.getElementById('taskParams');
    
    let paramsHtml = '';
    
    switch (taskType) {
        case 'generate':
            paramsHtml = `
                <label style="display: block; margin-bottom: 5px;">热点ID:</label>
                <input type="number" id="trendId" style="width: 100%; padding: 8px; border: 1px solid #ddd; border-radius: 4px; margin-bottom: 10px;" placeholder="请输入热点ID">
                <label style="display: block; margin-bottom: 5px;">目标平台:</label>
                <select id="platforms" multiple style="width: 100%; padding: 8px; border: 1px solid #ddd; border-radius: 4px;">
                    <option value="weibo">微博</option>
                    <option value="twitter">Twitter</option>
                    <option value="wechat">微信公众号</option>
                </select>
            `;
            break;
        case 'publish':
            paramsHtml = `
                <label style="display: block; margin-bottom: 5px;">内容ID:</label>
                <input type="number" id="contentId" style="width: 100%; padding: 8px; border: 1px solid #ddd; border-radius: 4px;" placeholder="请输入内容ID">
            `;
            break;
        case 'scrape':
            paramsHtml = `
                <label style="display: block; margin-bottom: 5px;">数据源:</label>
                <select id="sources" multiple style="width: 100%; padding: 8px; border: 1px solid #ddd; border-radius: 4px;">
                    <option value="weibo" selected>微博</option>
                    <option value="zhihu" selected>知乎</option>
                    <option value="baidu" selected>百度</option>
                </select>
            `;
            break;
        default:
            paramsHtml = '<p style="color: #666;">此任务无需额外参数</p>';
    }
    
    paramsContainer.innerHTML = paramsHtml;
}

function executeTask() {
    const taskType = document.getElementById('taskTypeSelect').value;
    if (!taskType) {
        alert('请选择任务类型');
        return;
    }
    
    let params = {};
    
    switch (taskType) {
        case 'generate':
            const trendId = document.getElementById('trendId').value;
            if (!trendId) {
                alert('请输入热点ID');
                return;
            }
            const platformSelects = document.getElementById('platforms').selectedOptions;
            const platforms = Array.from(platformSelects).map(option => option.value);
            params = { trend_id: parseInt(trendId), platforms };
            break;
        case 'publish':
            const contentId = document.getElementById('contentId').value;
            if (!contentId) {
                alert('请输入内容ID');
                return;
            }
            params = { content_id: parseInt(contentId) };
            break;
        case 'scrape':
            const sourceSelects = document.getElementById('sources').selectedOptions;
            const sources = Array.from(sourceSelects).map(option => option.value);
            params = { sources };
            break;
    }
    
    hideRunTaskModal();
    runTask(taskType, params);
}

function getTaskName(taskType) {
    const names = {
        'scrape': '热点抓取',
        'generate': '内容生成',
        'publish': '内容发布',
        'workflow': '自动工作流',
        'cleanup': '数据清理',
        'health': '健康检查'
    };
    return names[taskType] || taskType;
}

function refreshTasks() {
    loadTaskStatus();
    loadTaskHistory();
}

function showLoading(text) {
    document.getElementById('loadingText').textContent = text;
    document.getElementById('loadingModal').style.display = 'block';
}

function hideLoading() {
    document.getElementById('loadingModal').style.display = 'none';
}
</script>
{% endblock %}